<template>
  <view class="lottery-container">
    <!-- 用户资源显示区 -->
    <view class="resources-section">
      <view class="resource-item" @click="showExchangeModal('coins')">
        <text class="resource-icon">🪙</text>
        <text class="resource-value">{{ userCoins }}</text>
        <text class="add-btn">+</text>
      </view>
      <view class="resource-item" @click="showExchangeModal('points')">
        <text class="resource-icon">💎</text>
        <text class="resource-value">{{ userPoints }}</text>
        <text class="add-btn">+</text>
      </view>
      <view class="resource-item" @click="showExchangeModal('tickets')">
        <text class="resource-icon">🎫</text>
        <text class="resource-value">{{ lotteryTickets }}</text>
        <text class="add-btn">+</text>
      </view>
    </view>

    <!-- 抽奖转盘区域 -->
    <view class="wheel-section">
      <view class="wheel-container">
        <!-- 转盘背景 -->
        <view class="wheel" :style="{ transform: 'rotate(' + currentRotation + 'deg)' }">
          <!-- 奖品扇区 -->
          <view 
            class="prize-sector" 
            v-for="(prize, index) in prizes" 
            :key="prize.id"
            :style="getSectorStyle(index)"
          >
            <view class="sector-bg"></view>
            <view class="prize-content">
              <text class="prize-icon">{{ prize.icon }}</text>
              <text class="prize-name">{{ prize.name }}</text>
            </view>
          </view>
        </view>
        
        <!-- 指针 -->
        <view class="pointer">
          <text class="pointer-icon">▼</text>
        </view>
        
        <!-- 中心抽奖按钮 -->
        <view 
          class="center-btn" 
          :class="{ disabled: isSpinning }"
          @click="startLottery"
        >
          <text class="center-btn-text">{{ isSpinning ? '抽奖中...' : '开始抽奖' }}</text>
        </view>
      </view>
    </view>

    <!-- 抽奖方式选择 -->
    <view class="lottery-type-section">
      <view 
        class="type-btn" 
        :class="{ active: lotteryType === 'points' }"
        @click="switchLotteryType('points')"
      >
        <text class="type-icon">💎</text>
        <text class="type-text">积分抽奖</text>
        <text class="type-cost">{{ pointsCost }}积分</text>
      </view>
      <view 
        class="type-btn" 
        :class="{ active: lotteryType === 'ticket' }"
        @click="switchLotteryType('ticket')"
      >
        <text class="type-icon">🎫</text>
        <text class="type-text">抽奖券抽奖</text>
        <text class="type-cost">{{ ticketCost }}张</text>
      </view>
    </view>

    <!-- 底部功能区 -->
    <view class="bottom-section">
      <view class="bottom-btn" @click="viewPrizeList">
        <text class="bottom-btn-icon">🎁</text>
        <text class="bottom-btn-text">奖品列表</text>
      </view>
      <view class="bottom-btn" @click="viewWinningRecords">
        <text class="bottom-btn-icon">📋</text>
        <text class="bottom-btn-text">中奖记录</text>
      </view>
      <view class="bottom-btn" @click="viewProbability">
        <text class="bottom-btn-icon">📊</text>
        <text class="bottom-btn-text">查看概率</text>
      </view>
    </view>
  </view>
</template>

<script>
import pointsManager from '@/utils/points-manager.js'
import backpackManager from '@/utils/backpack-manager.js'
import lotteryManager from '@/utils/lottery-manager.js'
import goldManager from '@/utils/gold-manager.js'

export default {
  data() {
    return {
      // 用户资源
      userCoins: 0,
      userPoints: 0,
      lotteryTickets: 0,
      
      // 抽奖配置
      lotteryType: 'points', // 'points' | 'ticket'
      pointsCost: 50,
      ticketCost: 1,
      
      // 转盘状态
      isSpinning: false,
      currentRotation: 0,
      
      // 奖品配置
      prizes: [
        {
          id: 1,
          name: '传说级武器',
          icon: '⚔️',
          type: 'weapon',
          rarity: 'legendary',
          probability: 5,
          value: 1000,
          description: '散发神秘光芒的传说武器'
        },
        {
          id: 2,
          name: '史诗皮肤',
          icon: '🎨',
          type: 'skin',
          rarity: 'epic',
          probability: 10,
          value: 500,
          description: '华丽的史诗级皮肤'
        },
        {
          id: 3,
          name: '稀有道具',
          icon: '💎',
          type: 'prop',
          rarity: 'rare',
          probability: 15,
          value: 200,
          description: '珍贵的稀有道具'
        },
        {
          id: 4,
          name: '积分奖励',
          icon: '💰',
          type: 'points',
          rarity: 'common',
          probability: 20,
          value: 100,
          description: '获得100积分'
        },
        {
          id: 5,
          name: '神秘盲盒',
          icon: '📦',
          type: 'blindbox',
          rarity: 'rare',
          probability: 15,
          value: 150,
          description: '神秘的盲盒道具'
        },
        {
          id: 6,
          name: '抽奖券x3',
          icon: '🎫',
          type: 'ticket',
          rarity: 'common',
          probability: 20,
          value: 150,
          description: '获得3张抽奖券'
        },
        {
          id: 7,
          name: '经验加成卡',
          icon: '⭐',
          type: 'prop',
          rarity: 'common',
          probability: 10,
          value: 50,
          description: '经验获取加成道具'
        },
        {
          id: 8,
          name: '谢谢参与',
          icon: '🎈',
          type: 'none',
          rarity: 'common',
          probability: 5,
          value: 0,
          description: '很遗憾，下次再来'
        }
      ]
    }
  },
  
  onLoad(options) {
    this.loadUserResources()
    
    // 如果从背包使用抽奖券进入，自动切换到抽奖券模式
    if (options.useTicket === 'true') {
      this.lotteryType = 'ticket'
    }
    
    // 初始化测试数据（首次使用时）
    this.initTestDataIfNeeded()
  },
  
  onShow() {
    this.loadUserResources()
  },
  
  methods: {
    // 显示兑换弹窗
    showExchangeModal(type) {
      let title = ''
      let content = ''
      
      if (type === 'coins') {
        title = '💰 金币兑换'
        content = '金币可用于购买商品和兑换其他资源\n\n兑换比例：\n• 1钻石 = 10金币\n• 10积分 = 1金币\n\n是否前往商城获取更多金币？'
      } else if (type === 'points') {
        title = '💎 积分兑换'
        content = '积分可用于抽奖和购买商品\n\n兑换比例：\n• 1钻石 = 50积分\n• 100金币 = 10积分\n\n是否前往任务中心获取更多积分？'
      } else if (type === 'tickets') {
        title = '🎫 抽奖券兑换'
        content = '抽奖券可用于参与抽奖\n\n兑换比例：\n• 1钻石 = 2张抽奖券\n• 50积分 = 1张抽奖券\n• 500金币 = 1张抽奖券\n\n是否使用资源兑换抽奖券？'
      }
      
      uni.showModal({
        title: title,
        content: content,
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            if (type === 'tickets') {
              this.showTicketExchangeOptions()
            } else {
              uni.showToast({
                title: '功能开发中',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 显示抽奖券兑换选项
    showTicketExchangeOptions() {
      uni.showActionSheet({
        itemList: [
          `用50积分兑换1张抽奖券 (当前积分: ${this.userPoints})`,
          `用500金币兑换1张抽奖券 (当前金币: ${this.userCoins})`
        ],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 用积分兑换
            this.exchangeTicketWithPoints()
          } else if (res.tapIndex === 1) {
            // 用金币兑换
            this.exchangeTicketWithCoins()
          }
        }
      })
    },
    
    // 用积分兑换抽奖券
    exchangeTicketWithPoints() {
      if (this.userPoints < 50) {
        uni.showToast({
          title: '积分不足',
          icon: 'none'
        })
        return
      }
      
      const success = pointsManager.spendPoints(50, '兑换抽奖券')
      if (success) {
        lotteryManager.addLotteryTickets(1)
        this.loadUserResources()
        uni.showToast({
          title: '兑换成功！',
          icon: 'success'
        })
      }
    },
    
    // 用金币兑换抽奖券
    exchangeTicketWithCoins() {
      if (this.userCoins < 500) {
        uni.showToast({
          title: '金币不足',
          icon: 'none'
        })
        return
      }
      
      // 扣除金币
      const success = goldManager.spendGold(500, '兑换抽奖券')
      if (success) {
        // 增加抽奖券
        lotteryManager.addLotteryTickets(1)
        this.loadUserResources()
        
        uni.showToast({
          title: '兑换成功！',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: '兑换失败',
          icon: 'none'
        })
      }
    },
    
    // 显示规则说明
    showRules() {
      const rulesText = `【抽奖规则】

1. 抽奖方式
   • 积分抽奖：消耗${this.pointsCost}积分
   • 抽奖券抽奖：消耗${this.ticketCost}张抽奖券

2. 奖品说明
   • 传说级武器：超稀有奖品
   • 史诗皮肤：高级皮肤道具
   • 稀有道具：珍贵游戏道具
   • 积分奖励：直接获得积分
   • 神秘盲盒：随机道具盲盒
   • 抽奖券x3：获得3张抽奖券
   • 经验加成卡：经验加成道具
   • 谢谢参与：未中奖

3. 注意事项
   • 每次抽奖随机获得一个奖品
   • 中奖概率公开透明
   • 奖品自动发放到背包
   • 抽奖记录保存最近20条

祝您好运！🍀`

      uni.showModal({
        title: '❓ 抽奖规则',
        content: rulesText,
        showCancel: false,
        confirmText: '知道了'
      })
    },
    
    // 加载用户资源
    loadUserResources() {
      this.userCoins = goldManager.getCurrentGold()
      this.userPoints = pointsManager.getCurrentPoints()
      this.lotteryTickets = lotteryManager.getLotteryTickets()
    },
    
    // 切换抽奖方式
    switchLotteryType(type) {
      if (this.isSpinning) {
        return
      }
      this.lotteryType = type
    },
    
    // 获取扇区样式
    getSectorStyle(index) {
      const angle = 360 / this.prizes.length
      const rotation = angle * index
      
      // 交替颜色
      const colors = ['#FFD700', '#FFA500', '#FF6B6B', '#FF8E53', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
      const backgroundColor = colors[index % colors.length]
      
      return {
        transform: `rotate(${rotation}deg)`,
        backgroundColor: backgroundColor
      }
    },
    
    // 开始抽奖
    startLottery() {
      if (this.isSpinning) {
        return
      }

      // 验证资源是否足够
      const checkResult = lotteryManager.canDraw(
        this.lotteryType,
        this.userPoints,
        this.lotteryTickets,
        this.pointsCost,
        this.ticketCost
      )

      if (!checkResult.canDraw) {
        uni.showToast({
          title: checkResult.reason,
          icon: 'none',
          duration: 2000
        })
        return
      }

      // 扣除资源
      let deductSuccess = false
      if (this.lotteryType === 'points') {
        deductSuccess = pointsManager.spendPoints(this.pointsCost, '参与抽奖')
      } else {
        deductSuccess = lotteryManager.reduceLotteryTickets(this.ticketCost)
      }

      if (!deductSuccess) {
        uni.showToast({
          title: '资源扣除失败',
          icon: 'none'
        })
        return
      }

      // 执行抽奖
      try {
        const prize = lotteryManager.draw(this.prizes)
        console.log('中奖奖品:', prize)

        // 播放转盘动画
        this.playSpinAnimation(prize)
      } catch (error) {
        console.error('抽奖失败:', error)
        // 退还资源
        this.refundResource()
        uni.showToast({
          title: '抽奖失败，请重试',
          icon: 'none'
        })
      }
    },

    // 退还资源
    refundResource() {
      if (this.lotteryType === 'points') {
        pointsManager.addPoints(this.pointsCost, '抽奖失败退还')
      } else {
        lotteryManager.addLotteryTickets(this.ticketCost)
      }
    },

    // 播放转盘动画
    playSpinAnimation(targetPrize) {
      this.isSpinning = true

      // 计算目标角度
      const prizeIndex = this.prizes.findIndex(p => p.id === targetPrize.id)
      const sectorAngle = 360 / this.prizes.length
      const targetAngle = prizeIndex * sectorAngle

      // 计算最终旋转角度（至少旋转5圈 + 目标角度）
      const minRotations = 5
      const finalRotation = 360 * minRotations + (360 - targetAngle) + sectorAngle / 2

      // 执行旋转动画
      this.currentRotation += finalRotation

      // 动画结束后显示结果
      setTimeout(() => {
        this.showWinningResult(targetPrize)
        this.isSpinning = false
      }, 3000) // 3秒动画时间
    },

    // 显示中奖结果
    showWinningResult(prize) {
      // 发放奖品
      const distributeSuccess = this.distributePrize(prize)

      if (!distributeSuccess && prize.type !== 'none') {
        // 奖品发放失败，退还资源
        this.refundResource()
        uni.showModal({
          title: '奖品发放失败',
          content: '很抱歉，奖品发放失败，已退还您的消耗。请联系客服处理。',
          showCancel: false
        })
        return
      }

      // 保存中奖记录
      lotteryManager.saveWinningRecord({
        prizeName: prize.name,
        prizeIcon: prize.icon,
        prizeType: prize.type,
        costType: this.lotteryType,
        costAmount: this.lotteryType === 'points' ? this.pointsCost : this.ticketCost
      })

      // 重新加载资源
      this.loadUserResources()

      // 显示中奖弹窗
      const resultText = prize.type === 'none' 
        ? '很遗憾，下次再来！' 
        : `恭喜获得 ${prize.name}！\n\n${prize.description}`

      uni.showModal({
        title: prize.type === 'none' ? '😢 谢谢参与' : '🎉 恭喜中奖',
        content: resultText,
        showCancel: false,
        confirmText: '太棒了！',
        success: () => {
          // 可以在这里添加庆祝动画
        }
      })
    },

    // 发放奖品
    distributePrize(prize) {
      try {
        switch (prize.type) {
          case 'weapon':
          case 'skin':
          case 'prop':
          case 'blindbox':
            // 添加到背包
            const item = {
              name: prize.name,
              icon: prize.icon,
              type: prize.type,
              typeText: this.getTypeText(prize.type),
              description: prize.description,
              quantity: 1,
              price: prize.value,
              canUse: ['prop', 'blindbox'].includes(prize.type),
              canSell: true
            }
            return backpackManager.addItem(item)

          case 'points':
            // 增加积分
            return pointsManager.addPoints(prize.value, '抽奖获得')

          case 'ticket':
            // 增加抽奖券（抽奖券x3）
            return lotteryManager.addLotteryTickets(3)

          case 'none':
            // 谢谢参与，不发放奖品
            return true

          default:
            console.warn('未知的奖品类型:', prize.type)
            return false
        }
      } catch (error) {
        console.error('发放奖品失败:', error)
        return false
      }
    },

    // 获取类型文本
    getTypeText(type) {
      const typeMap = {
        'weapon': '武器',
        'skin': '皮肤',
        'prop': '道具',
        'blindbox': '盲盒',
        'lottery': '抽奖',
        'pet': '宠物',
        'vehicle': '载具'
      }
      return typeMap[type] || '其他'
    },
    
    // 查看奖品列表
    viewPrizeList() {
      const prizeListText = this.prizes.map((prize, index) => {
        return `${index + 1}. ${prize.icon} ${prize.name}\n   ${prize.description}`
      }).join('\n\n')

      uni.showModal({
        title: '🎁 奖品列表',
        content: prizeListText,
        showCancel: false,
        confirmText: '知道了'
      })
    },
    
    // 查看中奖记录
    viewWinningRecords() {
      const records = lotteryManager.getWinningRecords()

      if (records.length === 0) {
        uni.showModal({
          title: '📋 中奖记录',
          content: '暂无中奖记录\n\n快去参与抽奖吧！',
          showCancel: false,
          confirmText: '知道了'
        })
        return
      }

      // 格式化记录
      const recordsText = records.slice(0, 10).map((record, index) => {
        const costText = record.costType === 'points' 
          ? `${record.costAmount}积分` 
          : `${record.costAmount}张抽奖券`
        return `${index + 1}. ${record.prizeIcon} ${record.prizeName}\n   消耗: ${costText}\n   时间: ${lotteryManager.getRelativeTime(record.timestamp)}`
      }).join('\n\n')

      uni.showModal({
        title: `📋 中奖记录 (最近${Math.min(records.length, 10)}条)`,
        content: recordsText,
        showCancel: false,
        confirmText: '知道了'
      })
    },
    
    // 查看概率
    viewProbability() {
      const probabilityText = this.prizes.map((prize, index) => {
        const rarityText = this.getRarityText(prize.rarity)
        return `${index + 1}. ${prize.icon} ${prize.name}\n   ${rarityText} | 概率: ${prize.probability}%`
      }).join('\n\n')

      uni.showModal({
        title: '📊 中奖概率',
        content: probabilityText + '\n\n所有概率总和: 100%',
        showCancel: false,
        confirmText: '知道了'
      })
    },

    // 获取稀有度文本
    getRarityText(rarity) {
      const rarityMap = {
        'legendary': '⭐⭐⭐⭐⭐ 传说',
        'epic': '⭐⭐⭐⭐ 史诗',
        'rare': '⭐⭐⭐ 稀有',
        'common': '⭐⭐ 普通'
      }
      return rarityMap[rarity] || '普通'
    },

    // 初始化测试数据（首次使用时）
    initTestDataIfNeeded() {
      const tickets = lotteryManager.getLotteryTickets()
      const gold = goldManager.getCurrentGold()
      
      // 如果抽奖券数量为0，初始化一些测试数据
      if (tickets === 0) {
        lotteryManager.setLotteryTickets(3)
        console.log('已初始化3张抽奖券用于测试')
      }
      
      // 如果金币为0，初始化一些测试金币
      if (gold === 0) {
        goldManager.addGold(1000, '新手礼包')
        this.userCoins = 1000
        console.log('已初始化1000金币用于测试')
      }
    }
  }
}
</script>

<style scoped>
.lottery-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 40rpx;
}

/* 用户资源显示区 */
.resources-section {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 30rpx;
  gap: 20rpx;
}

.resource-item {
  position: relative;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  padding: 12rpx 24rpx;
  border-radius: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.resource-item:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
}

.resource-icon {
  font-size: 32rpx;
  margin-right: 8rpx;
}

.resource-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-right: 8rpx;
}

.add-btn {
  font-size: 28rpx;
  color: #667eea;
  font-weight: bold;
  width: 32rpx;
  height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 50%;
}

/* 抽奖转盘区域 */
.wheel-section {
  padding: 40rpx 30rpx;
}

.wheel-container {
  position: relative;
  width: 600rpx;
  height: 600rpx;
  margin: 0 auto;
}

.wheel {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  position: relative;
  transition: transform 3s cubic-bezier(0.25, 0.1, 0.25, 1);
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.3);
  border: 8rpx solid #fff;
  background: #fff;
  overflow: hidden;
}

.prize-sector {
  position: absolute;
  width: 50%;
  height: 50%;
  left: 50%;
  top: 0;
  transform-origin: 0 100%;
  overflow: hidden;
}

.prize-sector::before {
  content: '';
  position: absolute;
  width: 200%;
  height: 200%;
  left: 0;
  top: 0;
  transform-origin: 0 100%;
}

.sector-bg {
  display: none;
}

.prize-content {
  position: absolute;
  top: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120rpx;
  z-index: 1;
}

.prize-icon {
  font-size: 48rpx;
  margin-bottom: 8rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.prize-name {
  font-size: 20rpx;
  color: #333;
  font-weight: bold;
  text-align: center;
  text-shadow: 0 1rpx 2rpx rgba(255, 255, 255, 0.8);
  line-height: 1.2;
  word-break: break-all;
}

.pointer {
  position: absolute;
  top: -30rpx;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
}

.pointer-icon {
  font-size: 60rpx;
  color: #ff4757;
  filter: drop-shadow(0 4rpx 8rpx rgba(0, 0, 0, 0.3));
}

.center-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 180rpx;
  height: 180rpx;
  background: linear-gradient(135deg, #ff6b6b, #ffa500);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 20rpx rgba(255, 107, 107, 0.4);
  z-index: 10;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.center-btn:active {
  transform: translate(-50%, -50%) scale(0.95);
  box-shadow: 0 4rpx 15rpx rgba(255, 107, 107, 0.5);
}

.center-btn.disabled {
  opacity: 0.6;
  background: linear-gradient(135deg, #ccc, #999);
  cursor: not-allowed;
}

.center-btn.disabled:active {
  transform: translate(-50%, -50%);
}

.center-btn-text {
  font-size: 28rpx;
  font-weight: bold;
  color: white;
  text-align: center;
}

/* 抽奖方式选择 */
.lottery-type-section {
  display: flex;
  justify-content: space-around;
  padding: 30rpx;
}

.type-btn {
  flex: 1;
  margin: 0 10rpx;
  background: rgba(255, 255, 255, 0.9);
  padding: 30rpx 20rpx;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.type-btn.active {
  background: linear-gradient(135deg, #667eea, #764ba2);
  transform: scale(1.05);
}

.type-icon {
  font-size: 48rpx;
  margin-bottom: 10rpx;
}

.type-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 5rpx;
}

.type-btn.active .type-text,
.type-btn.active .type-cost {
  color: white;
}

.type-cost {
  font-size: 24rpx;
  color: #666;
}

/* 底部功能区 */
.bottom-section {
  display: flex;
  justify-content: space-around;
  padding: 30rpx;
}

.bottom-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  padding: 20rpx 30rpx;
  border-radius: 15rpx;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.bottom-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.15);
}

.bottom-btn-icon {
  font-size: 40rpx;
  margin-bottom: 8rpx;
}

.bottom-btn-text {
  font-size: 24rpx;
  color: #333;
}
</style>
